package cn.javabb.admin.config;

import cn.javabb.admin.interceptor.MyInterceptor;
import cn.javabb.common.utils.SpringContextUtil;
import cn.javabb.common.utils.ThUtil;
import cn.javabb.core.model.ConfigKeyEnum;
import cn.javabb.core.service.sys.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author QINB imqinbao@163.com
 * @CreateDate 2019/1/11/011 18:36
 * @Since V1.0
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private ThUtil thUtil;
    @Resource
    private MyInterceptor myInterceptor;
    @Resource(name="thymeleafViewResolver")
    private ThymeleafViewResolver thymeleafViewResolver;
    /**
     * @param registry 配置静态资源放行
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        SysConfigService configService = SpringContextUtil.getBean(SysConfigService.class);
        String localFilePath = configService.getConfigValue(ConfigKeyEnum.ROOT_PATH.getKey());
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    /**
     * @param registry 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加自定义处理器
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor);
        //排除配置
        interceptorRegistration.excludePathPatterns("/assets/**");
        //配置拦截策略
        interceptorRegistration.addPathPatterns("/**");
    }
    /**
     * 网站跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET","POST","DELETE","PUT")
                .maxAge(3600);
    }
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        if (thymeleafViewResolver != null) {
            SysConfigService configService = SpringContextUtil.getBean(SysConfigService.class);
            Map<String, Object> vars = new HashMap<>();
            vars.put("config", configService.getConfigs(null));
            vars.put("thUtil",thUtil);
            thymeleafViewResolver.setStaticVariables(vars);
        }
        WebMvcConfigurer.super.configureViewResolvers(registry);
    }
}
